<template>
  <div>
    <div style="padding:8px 0" v-if="title">{{title}}</div>
    <el-upload
      :disabled="disabled"
      list-type="picture-card"
      accept="image/jpeg,image/gif,image/png"
      :on-preview="handlePictureCardPreview"
      :limit="3"
      :headers = "headers"
      :file-list.sync = "files"
      :before-upload = "beforeUpload"
      :on-exceed = "exceed"
      :on-remove = "remove"
      :on-error = "error"
      :on-success = "success"
      :action="getUploadUrl()">
      <i class="el-icon-plus" v-if="!disabled"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" style="max-width:100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        headers: {
          token: this.$cookie.get('token')  //从cookie里获取token，并赋值  Authorization ，而不是token
        },
        dialogImageUrl: '',
        dialogVisible: false
      }
    },
    props:{
      files:{
        default:function(){
          return []
        },
        type:Array
      },
      disabled:{
        function(){
          return false;
        },
        type:Boolean
      },
      title:{
        function(){
          return '';
        },
        type:String
      }
    },
    methods: {
      getUploadUrl () {
        return this.$http.adornUrl('/fileUpload')
      },
      beforeUpload(file){
        if (file.size > 1024 *1024 * 2) {
            this.$message.error("文件不能超过2M, 请重新上传!");
            return false;
        }
         let ext = file.name.substring(file.name.lastIndexOf('.')+1).toLowerCase()
         if(ext!='jpg'&&ext!='png'&&ext!='gif'){
            this.$message.error("文件格式限制于 jpg,png,gif");
            return false;
         }
      },
      exceed(){
        this.$message.error('最多只能上传3个附件')
      },
      remove(file, fileList){
        this.files.splice(this.files.findIndex(item => item == file), 1)
      },
      error(err, file, fileList){
        this.$message.error(err)
      },
      success(response, file, fileList){
        //console.log(this.files)
        if(response.code === 0){
          this.files.length = 0;
          this.files.push(...fileList);
           //name, response.url
          //this.fileWrap.attachments = fileList
          console.log(this.files)
        }
        else{
          this.$message.error(response.msg)
        }
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }
    }
  }
</script>
<style>
  .el-upload__tip{
    padding-left: 10px;
  }
.el-upload--picture-card, .el-upload-list--picture-card .el-upload-list__item{
    width: 70px;
    height: 70px;
    line-height: 70px;
}

</style>
